package com.yyj.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.yyj.enums.PaymentTypeEnum;
import com.yyj.exception.BaseException;
import com.yyj.model.TPropertyManager;
import com.yyj.model.TPropertyOwner;
import com.yyj.model.TPropertyPayment;
import com.yyj.model.TPropertyUserForm;
import com.yyj.util.DateUtil;
import com.yyj.util.WeixinUtil;
import com.yyj.web.protocol.req.PushMsgRepairReq;
import com.yyj.web.protocol.req.PushMsgWaterBillReq;
import com.yyj.web.protocol.req.PushRepairOrderReq;
import com.yyj.web.protocol.resp.ManagerResp;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 模板消息推送
 */
@Service
public class PushMessageService {

    public static final Logger logger = LoggerFactory.getLogger(PushMessageService.class);


    @Autowired
    ConfigService configService;

    @Autowired
    UserService userService;

    @Autowired
    ManagerService managerService;

    @Autowired
    UserFormService userFormService;

    @Autowired
    AppService appService;

    public void pushPayResultToOwners(TPropertyPayment paymentObj, String openId) throws Exception {
        JSONObject jsonMsg = new JSONObject();
        Map<String, Map<String, String>> dataMap = Maps.newHashMap();
        Map<String, String> keyword1Map = Maps.newHashMap();
        String feeDate = paymentObj.getFeeDate();
        String feeDate_ = feeDate.substring(4, 6).startsWith("0") ? feeDate.substring(5, 6) : feeDate.substring(4, 6);
        keyword1Map.put("value", feeDate_ + "月" + PaymentTypeEnum.getActivityCode(paymentObj.getType()).getDesc());
        dataMap.put("keyword1", keyword1Map);

        Map<String, String> keyword2Map = Maps.newHashMap();
        keyword2Map.put("value", paymentObj.getAmount() + "元");
        dataMap.put("keyword2", keyword2Map);

        Map<String, String> keyword3Map = Maps.newHashMap();
        keyword3Map.put("value", DateUtil.format(paymentObj.getUpdateTime() , DateUtil.sdfLongTimePlus));
        dataMap.put("keyword3", keyword3Map);

        Map<String, String> keyword4Map = Maps.newHashMap();
        keyword4Map.put("value", "本月费用已交，详情请查看交费历史");
        dataMap.put("keyword4", keyword4Map);

        Map<String, String> keyword5Map = Maps.newHashMap();
        keyword5Map.put("value", "获取更多小区信息，请关注“雅怡居”公众号");
        dataMap.put("keyword5", keyword5Map);

        jsonMsg.put("data", dataMap);
        jsonMsg.put("touser", openId);
        jsonMsg.put("template_id", configService.getConfigInfo("PAY_SUCCESS_MSG_TEMPLATE_ID").getConfigAttr());
        TPropertyUserForm userForm = userFormService.queryUserForm(openId);
        if (null == userForm) {
            logger.info("form_id获取失败");
            return;
        }
        jsonMsg.put("form_id", userForm.getFormId());
        String feeType = "";
        if(PaymentTypeEnum.WATER_FEE.getCode().equals(paymentObj.getType())){
            feeType = "water";
        }
        if(PaymentTypeEnum.MANAGE_FEE.getCode().equals(paymentObj.getType())){
            feeType = "manage";
        }

        jsonMsg.put("page", configService.getConfigInfo("PAY_SUCCESS_MSG_PAGE_URL").getConfigAttr()
                .replace("FEETYPE" , feeType)
                .replace("STATUS", "IS_PAY")
                .replace("FEEDATE", DateUtil.getNowShortDate().substring(0, 6))
        );
        WeixinUtil.sendTemplateMsg(appService.getAccessToken(), jsonMsg);
    }

    public void pushRepairResultToOwners(PushMsgRepairReq pushMsgRepairReq) throws Exception {
        JSONObject jsonMsg = new JSONObject();
        Map<String, Map<String, String>> dataMap = Maps.newHashMap();
        Map<String, String> keyword1Map = Maps.newHashMap();
        keyword1Map.put("value", pushMsgRepairReq.getContent());
        dataMap.put("keyword1", keyword1Map);

        Map<String, String> keyword2Map = Maps.newHashMap();
        keyword2Map.put("value", DateUtil.format(pushMsgRepairReq.getCreateTime() , DateUtil.sdfLongTimePlus));
        dataMap.put("keyword2", keyword2Map);

        Map<String, String> keyword3Map = Maps.newHashMap();
        keyword3Map.put("value", pushMsgRepairReq.getRepairStatement());
        dataMap.put("keyword3", keyword3Map);

        Map<String, String> keyword4Map = Maps.newHashMap();
        keyword4Map.put("value", pushMsgRepairReq.getMobile());
        dataMap.put("keyword4", keyword4Map);

        jsonMsg.put("data", dataMap);

        TPropertyOwner ownerObj = userService.findOwnerByMobile(pushMsgRepairReq.getMobile());
        if(null == ownerObj || StringUtils.isBlank(ownerObj.getOpenId()) || ownerObj.getOpenId().startsWith("wx-")){
            logger.info("用户不存在或者openId无效");
            return;
        }
        jsonMsg.put("touser", ownerObj.getOpenId());
        jsonMsg.put("template_id", configService.getConfigInfo("REPAIR_RESULT_MSG_TEMPLATE_ID").getConfigAttr());
        TPropertyUserForm userForm = userFormService.queryUserForm(ownerObj.getOpenId());
        if (null == userForm) {
            throw new BaseException("form_id获取失败");
        }
        jsonMsg.put("form_id", userForm.getFormId());
        jsonMsg.put("page", configService.getConfigInfo("REPAIR_RESULT_MSG_PAGE_URL").getConfigAttr()
                .replace("ID", pushMsgRepairReq.getId()+"")
        );
        WeixinUtil.sendTemplateMsg(appService.getAccessToken(), jsonMsg);
    }

    public void pushWaterResultToOwners(PushMsgWaterBillReq pushMsgWaterBillReq) throws Exception {
        JSONObject jsonMsg = new JSONObject();
        Map<String, Map<String, String>> dataMap = Maps.newHashMap();
        Map<String, String> keyword1Map = Maps.newHashMap();
        keyword1Map.put("value", pushMsgWaterBillReq.getFeeDate() + "水费数据审核");
        dataMap.put("keyword1", keyword1Map);

        Map<String, String> keyword2Map = Maps.newHashMap();
        keyword2Map.put("value",pushMsgWaterBillReq.getStatus());
        dataMap.put("keyword2", keyword2Map);

        Map<String, String> keyword3Map = Maps.newHashMap();
        keyword3Map.put("value", DateUtil.format(pushMsgWaterBillReq.getCreateTime() , DateUtil.sdfLongTimePlus));
        dataMap.put("keyword3", keyword3Map);

        Map<String, String> keyword4Map = Maps.newHashMap();
        keyword4Map.put("value", pushMsgWaterBillReq.getContact());
        dataMap.put("keyword4", keyword4Map);

        Map<String, String> keyword5Map = Maps.newHashMap();
        keyword5Map.put("value", pushMsgWaterBillReq.getRemark());
        dataMap.put("keyword5", keyword5Map);

        jsonMsg.put("data", dataMap);

        TPropertyOwner ownerObj = userService.findOwnerByMobile(pushMsgWaterBillReq.getMobile());
        if(null == ownerObj || StringUtils.isBlank(ownerObj.getOpenId()) || ownerObj.getOpenId().startsWith("wx-")){
            logger.info("用户不存在或者openId无效");
            return;
        }
        jsonMsg.put("touser", ownerObj.getOpenId());
        jsonMsg.put("template_id", configService.getConfigInfo("WATER_MSG_TEMPLATE_ID").getConfigAttr());
        TPropertyUserForm userForm = userFormService.queryUserForm(ownerObj.getOpenId());
        if (null == userForm) {
            logger.info("form_id获取失败");
            return;
        }
        jsonMsg.put("form_id", userForm.getFormId());
        jsonMsg.put("page", configService.getConfigInfo("PAYMENT_MSG_PAGE_URL").getConfigAttr()
                        .replace("FEETYPE" , "water")
                        .replace("STATUS", "NO_PAY")
                        .replace("FEEDATE", DateUtil.getNowShortDate().substring(0, 6))
                        .replace("ID", pushMsgWaterBillReq.getWaterBillId()+""));
        WeixinUtil.sendTemplateMsg(appService.getAccessToken(), jsonMsg);
    }


    public void pushRepairOrderToManager(PushRepairOrderReq pushRepairOrderReq) throws Exception {
        JSONObject jsonMsg = new JSONObject();
        Map<String, Map<String, String>> dataMap = Maps.newHashMap();
        Map<String, String> keyword1Map = Maps.newHashMap();
        keyword1Map.put("value", "故障报修工单");
        dataMap.put("keyword1", keyword1Map);

        Map<String, String> keyword2Map = Maps.newHashMap();
        keyword2Map.put("value",DateUtil.format(pushRepairOrderReq.getCreateTime() , DateUtil.sdfLongTimePlus));
        dataMap.put("keyword2", keyword2Map);

        Map<String, String> keyword3Map = Maps.newHashMap();
        keyword3Map.put("value", pushRepairOrderReq.getMobile());
        dataMap.put("keyword3", keyword3Map);

        Map<String, String> keyword4Map = Maps.newHashMap();
        keyword4Map.put("value", pushRepairOrderReq.getRoomNum());
        dataMap.put("keyword4", keyword4Map);

        Map<String, String> keyword5Map = Maps.newHashMap();
        keyword4Map.put("value", pushRepairOrderReq.getContent());
        dataMap.put("keyword5", keyword5Map);

        jsonMsg.put("data", dataMap);

        List<TPropertyManager> managerList = managerService.queryValidManagers();
        for(TPropertyManager managerObj : managerList){
            if(null == managerObj || StringUtils.isBlank(managerObj.getOpenId()) || managerObj.getOpenId().startsWith("wx-")){
                logger.info("用户不存在或者openId无效");
                continue;
            }
            jsonMsg.put("touser", managerObj.getOpenId());
            jsonMsg.put("template_id", configService.getConfigInfo("REPAIR_ORDER_MSG_TEMPLATE_ID").getConfigAttr());
            TPropertyUserForm userForm = userFormService.queryUserForm(managerObj.getOpenId());
            if (null == userForm) {
                continue;
            }
            jsonMsg.put("form_id", userForm.getFormId());
            jsonMsg.put("page", configService.getConfigInfo("REPAIR_ORDER_MSG_PAGE_URL").getConfigAttr()
                    .replace("ID", pushRepairOrderReq.getId()+"")
            );
            WeixinUtil.sendTemplateMsg(appService.getAccessToken(), jsonMsg);
        }

    }
}
